#ifndef __M_BUFFER_HPP__
#define __M_BUFFER_HPP__

#include "util.hpp"
#include <vector>
#include<cassert>

namespace lyzlog
{
#define DEFAULT_BUFFER_SIZE (1 * 1024 * 1024)
#define THRESHOLD_BUFFER_SIZE (8 * 1024 * 1024)
#define INCREMENT_BUFFER_SIZE (10 * 1024 * 1024)
    class Buffer
    {
    public:
        Buffer() : _buffer(DEFAULT_BUFFER_SIZE), _readder_idx(0), _writer_idx(0)
        {
        }
        // 向缓冲区写入
        void push(const char *data, size_t len)
        {
            // 如果空间不够 1.扩容（测试环境） 2.返回错误（正式环境）
            // if(len > writeAbleSize()) return;
            ensureEnoughSize(len);
            // 1.将数据拷贝到缓冲区
            std::copy(data, data + len, &_buffer[_writer_idx]);
            // 2.移动写指针位置
            moveWrite(len);
        }
        // 获取可读数据开始地址
        const char* begin()
        {
            return &(_buffer[_readder_idx]);
        }
        // 获取可写数据长度
        size_t writeAbleSize()
        {
            return _buffer.size() - _writer_idx;
        }
        // 获取可读数据长度
        size_t readAbleSize()
        {
            return (_writer_idx - _readder_idx);
        }
        // 移动读数据位置
        void moveRead(size_t len)
        {
            assert(len <= readAbleSize());
            _readder_idx += len;
        }
        // 初始化缓冲区操作
        void reset()
        {
            _writer_idx = 0;
            _readder_idx = 0;
        }
        // 交换缓冲区
        void swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_writer_idx,buffer._writer_idx);
            std::swap(_readder_idx,buffer._readder_idx);
        }
        // 判断缓冲区是否为空
        bool empty()
        {
            return (_readder_idx == _writer_idx);
        }

    private:
        //移动写位置指针
        void moveWrite(size_t len)
        {
            assert(_writer_idx + len <= _buffer.size());
            _writer_idx += len;
        }
        void ensureEnoughSize(size_t len)
        {
            // 空间充足
            if (len < writeAbleSize())
                return;
            // 空间不足扩容
            size_t new_size = 0;
            // 没到阈值，2倍扩容个
            if (_buffer.size() < THRESHOLD_BUFFER_SIZE)
            {
                new_size = _buffer.size() * 2 + len;
            } // 到阈值，线性扩容
            else
            {
                new_size = _buffer.size() + INCREMENT_BUFFER_SIZE + len;
            }
            _buffer.resize(new_size);
        }

    private:
        std::vector<char> _buffer;
        size_t _readder_idx;
        size_t _writer_idx;
    };
}

#endif